package ui.fragment.intersionfragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.decoration.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.ListDialog;
import base.BaseBean;
import base.fragment.BaseSwipeFragment;
import bean.AnswerBean;
import bean.SubjectBean;
import bean.UnreadMsgBean;
import event.IntersionEvent;
import event.IntersionLeftEvent;
import event.IntersionNumber;
import student.andlei.com.student.R;
import ui.activity.MainActivity;
import utils.GsonUtils;
import utils.ImageLoaderUtils;
import view.WrapContentLinearLayoutManager;

/**
 * author : ChenHuiMing
 * date : 2018/9/14
 * email : 907399255@qq.com
 * description : 左边菜单列表
 */
public class IntersionAnswerFragment extends BaseSwipeFragment<AnswerBean.mList> {

    public static final String STATUS = "STATUS";
    public static final String STATUS_ANSWER_NO = "0";//未读
    public static final String STATUS_ANSWER_YES = "1";//已读

    public static final String GET_QA_LIST = "/Qa/getQaList";
    public static final String SUBJECT_URL = "/Qa/subject";

    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private EditText mEtQaContent;
    private TextView mTvSubject;

    private String mStatus;
    private String mSubjectId;
    private ListDialog mListDialog;

    public static IntersionAnswerFragment getInstance(String status) {
        IntersionAnswerFragment answerListFragment = new IntersionAnswerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(STATUS, status);
        answerListFragment.setArguments(bundle);
        return answerListFragment;
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.code == 200) {
            if (TextUtils.equals(action, SUBJECT_URL)) {
                SubjectBean detailBean = (SubjectBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), SubjectBean.class);
                chooseSubjectDialog(detailBean.list);
            }else if(action.equals("Qa/cancelNews")){
                post("Qa/getNewsNumber",BaseBean.class,false);
            }else if(action.equals("Qa/getNewsNumber")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,UnreadMsgBean.class);
                if(bean.count>0){
                    MainActivity.img_red_point.setText(bean.count+"");
                    MainActivity.img_red_point.setVisibility(View.VISIBLE);
                }else {
                    MainActivity.img_red_point.setVisibility(View.GONE);
                }
            }
        } else {
           // toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_intersion_answer;
    }

    @Override
    protected void findViews() {
        super.findViews();
        EventBus.getDefault().register(this);
        mSwipeRefreshLayout = getView(R.id.swipeRefreshLayout);
        mRecyclerView = getView(R.id.rcly_);

        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.gray)));
//        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.intersion_answer_header, mRecyclerView, false);
        mEtQaContent = getView(R.id.edittext_search);
        mTvSubject = getView(R.id.tv_subject);
//        getSwipeAdapter().addHeader(headerView);
    }

    @Override
    protected void formatViews() {
        mTvSubject.setOnClickListener(this);
        mEtQaContent.setOnEditorActionListener(mOnEditorActionListener);
        refresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void darkenBackground(Float bgcolor) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgcolor;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);
    }

    @Override
    protected void getBundle() {
        mStatus = (String) getArguments().get(STATUS);
    }

    private long lastClickTime = 0L;
    private static final int FAST_CLICK_DELAY_TIME = 500;  // 快速点击间隔

    @Override
    public void onClick(View view) {
        //防止重复点击
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
            return;
        }
        lastClickTime = System.currentTimeMillis();

        if (view == mTvSubject) {
            post(SUBJECT_URL, BaseBean.class, false);
        }
    }

    @Override
    public SwipeRefreshLayout getSwipeRefreshLayout() {
        return mSwipeRefreshLayout;
    }

    @Override
    public String getHttpUrl() {
        return GET_QA_LIST;
    }

    @Override
    public Map<String, Object> getMapParam() {
        Map<String, Object> map = new HashMap<>();
        map.put("qa_content", mEtQaContent.getText().toString());
        map.put("subject_id", mSubjectId);
        map.put("status", mStatus);
        return map;
    }

    boolean isFirstLoadData = true;

    @Override
    public SwipeData formatHttpData(boolean isRefresh, BaseBean baseBean) {
        AnswerBean bean = (AnswerBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), AnswerBean.class);
        SwipeData swipeData = new SwipeData();
        swipeData.list = bean.list;
        swipeData.currentPage = bean.page.cpage;
        swipeData.maxPage = bean.page.total_page;
        if (TextUtils.equals(mStatus, STATUS_ANSWER_NO)) {
            EventBus.getDefault().post(new IntersionNumber());
        }
        if (isRefresh && swipeData.list.size() > 0 && TextUtils.equals(mStatus, STATUS_ANSWER_NO) && isFirstLoadData) {
            isFirstLoadData = false;
            IntersionEvent intersionEvent = new IntersionEvent();
            intersionEvent.isDetailQa = true;
            intersionEvent.qa_id = swipeData.list.get(0).qa_id;
            EventBus.getDefault().post(intersionEvent);
        }
        return swipeData;
    }

    @Override
    public int getItemLayoutResId() {
        return R.layout.item_answer;
    }

    @Override
    public void viewConvert(final BaseViewHolder helper, AnswerBean.mList item) {
        final TextView textView = helper.getView(R.id.tv_question);
        ImageView imageView = helper.getView(R.id.iv_content);
        if (TextUtils.isEmpty(item.image)) {
            imageView.setVisibility(View.GONE);
        } else {
            imageView.setVisibility(View.VISIBLE);
            ImageLoaderUtils.loadImage(getActivity(), item.image, imageView);
        }
        textView.setText(item.content);
        helper.setText(R.id.tv_subject, item.subject_name).setText(R.id.tv_time, item.create_time);
    }

    @Override
    public void onItemClickListener(SwipeAdapter adapter, RecyclerView.ViewHolder vh, int position) {
        super.onItemClickListener(adapter, vh, position);
        AnswerBean.mList bean = (AnswerBean.mList) adapter.getItem(position);
        if (bean != null) {
            IntersionEvent intersionEvent = new IntersionEvent();
            intersionEvent.isDetailQa = true;
            intersionEvent.qa_id = bean.qa_id;
            EventBus.getDefault().post(intersionEvent);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("qa_id", bean.qa_id);
        post("Qa/cancelNews", map, BaseBean.class, false);
    }

    /**
     * 选择科目
     *
     * @param listBeans
     */
    private void chooseSubjectDialog(final List<SubjectBean.ListBean> listBeans) {
        final List<String> list = new ArrayList<>();
        for (SubjectBean.ListBean listBean : listBeans) {
            list.add(listBean.subject_name);
        }
        if (mListDialog != null && mListDialog.isShowing()) {
            mListDialog.dismiss();
        }
        mListDialog = new ListDialog(getActivity(), "选择科目", list);
        mListDialog.setListItemClickListener(new ListDialog.OnListItemClickListener() {
            @Override
            public void onItemClick(int position, String s) {
                mSubjectId = listBeans.get(position).subject_id;
                mTvSubject.setText(list.get(position));
                mListDialog.dismiss();
                refresh();
            }
        });
        mListDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });
        darkenBackground(0.5f);
        mListDialog.showAsDropDown(mTvSubject);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(IntersionLeftEvent event) {
        if (event.leftType == IntersionLeftEvent.TYPE_NO && TextUtils.equals(mStatus, STATUS_ANSWER_NO)) {
            refresh();
        }
    }

    /**
     * 搜索
     */
    TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            refresh();
            return true;
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        refresh();
//        if(!hidden){
//            refresh();
//        }
    }
}
